<?php

namespace app\task\command;

use app\event\OrderPayRefund;
use app\model\CouponOrder;
use app\task\cron\coupon\RefundOrder;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 出票失败退款.
 */
class CouponRefund extends Command
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        $this->setName('coupon:autoRefund')
            ->setDescription('coupon order auto refund');
    }

    /**
     * 执行指令.
     *
     * sudo -u www php /www/wwwroot/api/think coupon:autoRefund
     *
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        echo '权益充值失败订单自动退款--' . PHP_EOL;
        $lockKey = 'coupon_order_auto_refund_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

         CouponOrder::query()
            ->where('refund_status', CouponOrder::C_REFUND_STATUS_ING)
            ->where("status", 'in', [CouponOrder::C_STATUS_SUBMIT_FAIL, CouponOrder::C_STATUS_RECHARGE_FAIL])
            ->where("pay_status", CouponOrder::C_PAY_STATUS_YES)
            ->limit(30)
            ->order('updated_at asc')
            ->select()->each(function (CouponOrder $couponOrder) {
                echo '处理权益退款的订单:' . $couponOrder->id . PHP_EOL;
                event(new OrderPayRefund($couponOrder));
            });


        cache($lockKey, null);

    }
}
